package com.gagakuai.bpm.domian.events;



import com.gagakuai.bpm.common.constants.BpmMetaConstants;
import com.gagakuai.bpm.common.enums.BpmCompeleptedTypEnum;
import com.gagakuai.bpm.dao.mapper.ActHiTaskinstMapper;
import com.gagakuai.bpm.domian.dto.camunda.CompletedTypeDto;
import com.gagakuai.bpm.domian.entity.camuda.ActRuTask;
import com.gagakuai.bpm.utils.RedisUtil;
import com.gagakuai.bpm.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/*
 * @program: bpm_server
 * @description: 加签监听器
 * @author: houhong
 * @create: 2022-05-07 16:13
 */
@Component
@Slf4j
public class AddInstanceListener implements ApplicationListener<AddInstanceEvent> {


    private BpmCompeleptedTypEnum bpmCompeleptedTypEnum;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ActHiTaskinstMapper actHiTaskinstMapper;

    @Autowired
    private HistoryService historyService;


    @Async
    @Override
    public synchronized void onApplicationEvent(AddInstanceEvent addInstanceEvent) {

        log.info("=================进入到加签监听器=============");
        //在加签后--需要修改加签条件为 加签人和定义key
        bpmCompeleptedTypEnum = BpmCompeleptedTypEnum.ONE_COMPLETED;

        //这里走到了加签。所以需要先删除由于任务回调产生的非原始记录数据
        AddInstanceEvent.AddInstanceEventData addInstanceEventData = addInstanceEvent.getAddInstanceEventData();

        //加签任务
        List<ActRuTask> actRuTaskList = addInstanceEventData.getActRuTask();


        String processId = addInstanceEventData.getProcessId();

        StringBuffer redisKeyBuffer = new StringBuffer(BpmMetaConstants.BPM_COMPLETED_TYPE_GLOBAL)
                .append(BpmMetaConstants.REDIS_FILE_KEY_SEPTOR).append(processId);

        String redisKey = redisKeyBuffer.toString();

        Map<Object, Object> hmget = redisUtil.hmget(redisKey);

        CompletedTypeDto completedTypeDto = new CompletedTypeDto();
        try {
            BeanUtils.populate(completedTypeDto, hmget);

            //设置已加签
            completedTypeDto.setIsAddInstance(BpmMetaConstants.BPM_TASK_IS_ADD_INSTANCE);
            //设置该任务原来的人
            if (StringUtils.isEmpty(completedTypeDto.getOriginTaskOwnersStr())) {
                //走一次数据库
                String lastOwner = getLastOwner(processId);
                log.info("#原来的任务人:{}#", lastOwner);
                completedTypeDto.setOriginTaskOwnersStr(lastOwner);
            }
            String taskDefKey = completedTypeDto.getTaskDefKey();
            //此次加签办理人
            List<String> assigneeList = addInstanceEventData.getAssigneeList();
            //按照几人办毕完成
            String completedType = completedTypeDto.getCompletedType();
            //判断任务完成条件
            String completedCondition = completedTypeDto.getCompletedCondition();

            //加签人
            String addInstancesStr = completedTypeDto.getAddInstancesStr();


            //当前任务拥有人
            String taskOwner = addInstanceEventData.getTaskOwner();

            //多人办毕场景
            if (BpmCompeleptedTypEnum.ALL_COMPLETED.getCode().equals(completedType)) {

            }
            //一人办毕 构建完成人
            else if (BpmCompeleptedTypEnum.ONE_COMPLETED.getCode().equals(completedType)) {

                //加签人buffer
                StringBuffer addInstanceBuffer = new StringBuffer();

                if (StringUtils.isNonEmpty(addInstancesStr)) {
                    addInstanceBuffer.append(addInstancesStr);
                }

                for (String assignee : assigneeList) {

                    addInstanceBuffer.append(BpmMetaConstants.REDIS_CONDITION_KEY_SEPTOR)
                            .append(assignee);
                }
                /*
                 *
                 *  构建完成人:规则,直接在当前condition下面追加完成人 不准追加给同样的人
                 *
                 *  新规则：加签人+ 一个原来的人完成就好+ 所有加签的人
                 *
                 */
                log.info("#新构建的加签人={}#", addInstanceBuffer.toString());
                completedTypeDto.setAddInstancesStr(addInstanceBuffer.toString());
                Map<Object, Object> describe = BeanUtils.describe(completedTypeDto);
                redisUtil.hmset(redisKey, describe);

            }
            String originOwer = addInstanceEventData.getCurAddTaskOwner();
            log.info("#当前任务人的原始任务拥有者是:{}#", originOwer);
            //加签办理后.将任务拥有人设置为当前任务的拥有人 -- 排除原来就拥有的key
            //  actHiTaskinstMapper.updateTaskOwnerBatch(actRuTaskList, originOwer);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getLastOwner(String processInstanceId) {

        String redisKey = BpmMetaConstants.BPM_COMPLETED_TYPE_GLOBAL
                + BpmMetaConstants.REDIS_FILE_KEY_SEPTOR + processInstanceId;

        Map<Object, Object> hmget = redisUtil.hmget(redisKey);

        String taskDefKey = (String) hmget.get("taskDefKey");

        String addInstancesStr = (String) hmget.get("addInstancesStr");

        //所有的任务人
        List<String> orignWithAddInsaceUserList = new ArrayList<>();
        if (StringUtils.isNonEmpty(taskDefKey)) {


            List<HistoricTaskInstance> historyTaskList = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .taskDefinitionKey(taskDefKey)
                    .list();

            for (HistoricTaskInstance historicTaskInstance : historyTaskList) {

                String curTaskOwner = StringUtils.isNonEmpty(historicTaskInstance.getOwner()) ? historicTaskInstance.getOwner()
                        : historicTaskInstance.getAssignee();
                orignWithAddInsaceUserList.add(curTaskOwner);
            }
        }

        List<String> addInsaceList = new ArrayList<>();
        //获取所有的加签人
        if (StringUtils.isNonEmpty(addInstancesStr)) {
            String[] addInstanceArr = addInstancesStr.split(BpmMetaConstants.REDIS_CONDITION_KEY_SEPTOR);
            List<String> list = Arrays.asList(addInstanceArr);
            addInsaceList.addAll(list);
        }

        List<String> result = new ArrayList<>();
        //移除加签人
        result = orignWithAddInsaceUserList.stream().filter(
                b -> addInsaceList.stream().noneMatch(id -> Objects.equals(b, id))).collect(Collectors.toList());


        StringBuffer resultBuffer = new StringBuffer();
        for (String s : result) {

            resultBuffer.append(BpmMetaConstants.REDIS_CONDITION_KEY_SEPTOR)
                    .append(s);

        }
        return resultBuffer.toString();

    }

    public static void main(String[] args) {

        List<String> rest = new ArrayList<>();
        rest.add("123");
        rest.add("1233");


    }
}